/* GSCommunicationGwcsPro.java
 *
 * Project/Product: GWBS2009
 *
 * Modify Information:
 * =============================================================================
 *   Author	Date       Description
 *   ----------	---------- ---------------------------------------------------
 *   Administrator	2009-3-24	First release
 *
 * Licensed Materials - Property of APEP
 * =============================================================================
 *    (C) COPYRIGHT Shanghai Auto Mart E-Procurement Co., Ltd. 2007 - 2009
 *    All Rights Reserved.
 *
 *    This software is the confidential and proprietary information of
 *    Shanghai Auto Mart E-Procurement Co., Ltd. ("Confidential Information").
 *    You shall not disclose such Confidential Information and shall use it only
 *    in accordance with the terms of the license agreement you entered into 
 *    with Shanghai Auto Mart E-Procurement Co., Ltd.
 *
 * Noties:
 * =============================================================================
 * 
 */

package com.hitrust.gs.business;

import java.sql.Connection;
import java.util.ArrayList;

import com.apep.connect.APEPRequest;
import com.apep.connect.APEPResponse;
import com.apep.connect.APEPServiceException;
import com.apep.lib.xml.SampleElement;
import com.apep.lib.xml.SampleXMLDocument;
import com.hitrust.gs.bean.GSOrderAnaDetailAndCategoryBean;
import com.hitrust.gs.bean.GSOrderDetailBean;
import com.hitrust.gs.bean.GSOrderDetailQueryBean;
import com.hitrust.gs.dao.GSOrderDetailDAO;
import com.hitrust.gs.lib.GSBaseConstants;
import com.hitrust.gs.lib.GSLogWriter;
import com.hitrust.gs.lib.db.GSBaseDAO;
import com.hitrust.gs.service.GSBaseProcesser;
import com.hitrust.gs.util.date.DateUtil;
import com.hitrust.gs.util.lang.StringUtils;

import framework.core.LogWriter;
/**
 * 与子系统端交互业务类
 * **/
public class GSCommunicationGwcsPro implements GSBaseProcesser {
    private GSOrderDetailDAO detailDao=new GSOrderDetailDAO();
    public static String ROOT="Order";
    //根据送货单号取得订单明细
    public APEPResponse getOrderDetailGwcs(APEPRequest req){
        APEPResponse res = new APEPResponse();
        try {
            SampleXMLDocument xmlDocument=new SampleXMLDocument(req.toXml());
            String goodsId=xmlDocument.getValueNoNull("DELIVERGOODSID");
            if (goodsId==null||"".equals(goodsId)) {
                res.set("ResultCode", APEPServiceException.APEP_EXC_CODE_99);
                res.set("ErrorDesc","送货单号不存在！");
                return res;
            }
            ArrayList detailList= detailDao.getOrderDetailByGoodId(goodsId);
            if (detailList.size()==0) {
                res.set("ResultCode", APEPServiceException.APEP_EXC_CODE_99);
                res.set("ErrorDesc","送货单号没有对应订单信息或订单已完成！");
                return res;
            }
            String val=this.detailBeanToXml(detailList, goodsId);
            res.set("Data", val);
            res.setResultCode(APEPResponse.RESULT_SUCCESS);
            res.setErrorDesc("");
           
        } catch (Exception e) {
            if (e instanceof APEPServiceException) {
                APEPServiceException tAPEPException = (APEPServiceException) e;
                res.set("ResultCode", tAPEPException.getCode());
                res.set("ErrorDesc", e.getMessage());
            } else {
                res.set("ResultCode", APEPServiceException.APEP_EXC_CODE_99);
                res.set("ErrorDesc", e.getMessage());
                LogWriter.warn("ConnectProcessorV1::processCreateOrder() - " + e.getLocalizedMessage());
            }
        }
        return res;
    }
    
    public APEPResponse queryOrderDetail(APEPRequest req){
    	APEPResponse res = new APEPResponse();
    	GSOrderDetailQueryBean bean = new GSOrderDetailQueryBean();
    	try {
    		 SampleXMLDocument xmlDocument=new SampleXMLDocument(req.toXml());
    		 bean.setDrawingPieceCode(xmlDocument.getValueNoNull("DrawingPieceCode"));
    		 bean.setGsOrderTempId(xmlDocument.getValueNoNull("GsOrderTempId"));
    		 bean.setProductCode(xmlDocument.getValueNoNull("ProductCode"));
    		 bean.setGsOrderCreateDateStart(xmlDocument.getValueNoNull("GsOrderCreateDateStart"));
    		 bean.setGsOrderCreateDateEnd(xmlDocument.getValueNoNull("GsOrderCreateDateEnd"));
    		 bean.setWarehouseCode(xmlDocument.getValueNoNull("WarehouseCode"));
    		 bean.setGsOrderDetailStatus(xmlDocument.getValueNoNull("GsOrderDetailStatus"));
    		 bean.setProviderCode(xmlDocument.getValueNoNull("ProviderCode"));
    		
    		 bean.setPageSize(Integer.parseInt(xmlDocument.getValueNoNull("PageSize")));
    		 bean.setCurrentPage(Integer.parseInt(xmlDocument.getValueNoNull("CurentPage")));
             
             ArrayList list = detailDao.getOrderDetailListPage(bean);
    		 int count = detailDao.getOrderDetailListCount(bean);
    		 String data = this.orderDetailQueryBeanToXml(list);
             res.set("Data",data);
             res.set("TotalSize", String.valueOf(count));
             res.setResultCode(APEPResponse.RESULT_SUCCESS);
             res.setErrorDesc("");   		 
		} catch (Exception e) {
            if (e instanceof APEPServiceException) {
                APEPServiceException tAPEPException = (APEPServiceException) e;
                res.set("ResultCode", tAPEPException.getCode());
                res.set("ErrorDesc", e.getMessage());
            } else {
                res.set("ResultCode", APEPServiceException.APEP_EXC_CODE_99);
                res.set("ErrorDesc", "无相关订单信息！");
                LogWriter.warn("ConnectProcessorV1::processCreateOrder() - " + e.getLocalizedMessage());
            }
		}
    	return res;
    }
    


	private String orderDetailQueryBeanToXml(ArrayList list) {
		StringBuffer result =new StringBuffer();
		for (int i = 0; i < list.size(); i++) {
			GSOrderDetailQueryBean bean = (GSOrderDetailQueryBean) list.get(i);
			SampleElement element = new SampleElement("OrderDetail");
			element.addChildElement(new SampleElement("ProductID",bean.getProductId()));
			element.addChildElement(new SampleElement("ProductCode",bean.getProductCode()));
			element.addChildElement(new SampleElement("GsOrderDetailStatus",bean.getGsOrderDetailStatus()));
			element.addChildElement(new SampleElement("ProductName",bean.getProductName()));
			element.addChildElement(new SampleElement("GsDeliverGoosCounts",String.valueOf(bean.getGsDelicerGoodsCounts())));
			element.addChildElement(new SampleElement("ProductModel",bean.getProductMode()));
			element.addChildElement(new SampleElement("ProductSpec",bean.getProductSpec()));
			element.addChildElement(new SampleElement("DrawingPieceCode",bean.getDrawingPieceCode()));
			element.addChildElement(new SampleElement("GsGoodsUnitPrice",String.valueOf(bean.getGsGoodsUnitPrice())));
			element.addChildElement(new SampleElement("GsOrderTempId",bean.getGsOrderTempId()));
			element.addChildElement(new SampleElement("GsOrderCreateDate",bean.getGsOrderCreateDate()));
			element.addChildElement(new SampleElement("GsOrderDetailID",bean.getGsOrderDetailId()));
			element.addChildElement(new SampleElement("GSBalanceMode",bean.getGsBalanceMode()));
//			element.addChildElement(new SampleElement("TotalSize",String.valueOf(bean.getTotalCount())));
//			element.addChildElement(new SampleElement("PageSize",String.valueOf(bean.getPageSize())));
//			element.addChildElement(new SampleElement("CurentPage",String.valueOf(bean.getCurrentPage())));
			result.append(element.toString());
		}
		return result.toString();
	}

	//子系统签收信息写入
    public APEPResponse processFinishOrder(APEPRequest req){
        GSOrderDetailDAO tOrderDetailDAO=new GSOrderDetailDAO();
        Connection conn=tOrderDetailDAO.getConnetion();
        APEPResponse res=new APEPResponse();
        try {
            conn.setAutoCommit(false);
            SampleXMLDocument xmlDocument=new SampleXMLDocument(req.toXml());
            ArrayList tList= xmlDocument.getDocuments(ROOT);
            ArrayList tempList = new ArrayList();
            for (int i = 0; i <tList.size(); i++) {
                xmlDocument=(SampleXMLDocument) tList.get(i);
                String orderDetailId=xmlDocument.getValueNoNull("CusOrderItemCode");
               //根据传入的每条订单明细送货确认信息的订单编号查询订单明细
                GSOrderDetailBean tOrderDetailBean = tOrderDetailDAO.queryOrderDetailByDetailId(conn,orderDetailId);
                if(tOrderDetailBean != null){
                    tOrderDetailBean.setGs_deliver_goods_id(xmlDocument.getValueNoNull("SendCode"));
                    tOrderDetailBean.setGs_signin_date(xmlDocument.getValueNoNull("ReceiveTime").substring(0,10));
                    tOrderDetailBean.setGs_signin_time(xmlDocument.getValueNoNull("ReceiveTime").substring(10));
                    tOrderDetailBean.setGs_signin_count(Double.parseDouble(xmlDocument.getValueNoNull("ReceiveQty")));
                    tOrderDetailBean.setGs_signin_person(xmlDocument.getValueNoNull("ReceivePerson"));
                    tOrderDetailBean.setGs_signin_explain(xmlDocument.getValueNoNull("ReceiveRemark"));
                    tOrderDetailBean.setGs_goods_unitprice(Double.parseDouble(xmlDocument.getValueNoNull("SurePrice")));
                    tOrderDetailBean.setGs_order_detail_status(GSBaseConstants.ORDER_DELIVERY_CONFIRM);
                    tOrderDetailBean.setGs_lastmodify_contents("接收到子系统签收订单明细信息");
                    tOrderDetailBean.setGs_lastmodifer_id("仓储子系统");
                    tOrderDetailBean.setGs_lastmodify_date(getCurDT());
                    tempList.add(tOrderDetailBean);
                }else{
                    res.set("ResultCode", APEPServiceException.APEP_EXC_CODE_99); // 交易结果 - 成功返回
                    res.set("ErrorDesc", "订单明细编号不存在");
                    return res;
                }
            }
            boolean tFlag = false;
            for(int i=0; i<tempList.size();i++){
                GSOrderDetailBean tOrderDetailBean = (GSOrderDetailBean)tempList.get(i);
                tFlag = tOrderDetailDAO.updateOrderDetailStatus(tOrderDetailBean,conn,GSBaseConstants.ORDER_ORDER_CONFIRM);
                if(tFlag){
                    continue;
                }else{
                    GSLogWriter.debug(this,"修改订单明细状态为交货确认失败");
                    conn.rollback();
                    break;
                }
            }
            if(tFlag){
                conn.commit();
                //往apep发送该签收信息
                for (int i = 0; i < tList.size(); i++) {
                    xmlDocument=(SampleXMLDocument) tList.get(i);
                    GSCommunicationApepProcessor.sendOrderDetailSign(xmlDocument);
                }
            }else{
                res.set("ResultCode", APEPServiceException.APEP_EXC_CODE_99);
                res.set("ErrorDesc", "向交易平台发送订单签收信息失败");
            }
            if(tFlag){
                res.set("ResultCode", APEPResponse.RESULT_SUCCESS);
                res.set("ErrorDesc", "");
            }else{
                res.set("ResultCode", APEPServiceException.APEP_EXC_CODE_99);
                res.set("ErrorDesc", "修改订单明细状态为交货确认失败");
            }
        } catch (Exception e) {
            if (e instanceof APEPServiceException) {
                APEPServiceException tAPEPException = (APEPServiceException) e;
                res.set("ResultCode", tAPEPException.getCode());
                res.set("ErrorDesc", e.getMessage());
            } else {
                res.set("ResultCode", APEPServiceException.APEP_EXC_CODE_99);
                res.set("ErrorDesc", e.getMessage());
                LogWriter.warn("ConnectProcessorV1::processCreateOrder() - " + e.getLocalizedMessage());
            }
        }finally{
           GSBaseDAO.close(conn);
        }
        return res;
    }
    private String detailBeanToXml(ArrayList detailList,String goodsId){
        StringBuffer result=new StringBuffer();
        for (int i = 0; i < detailList.size(); i++) {
            GSOrderAnaDetailAndCategoryBean detailBean=(GSOrderAnaDetailAndCategoryBean) detailList.get(i);
            SampleElement element=new SampleElement("Order");
            element.addChildElement(new SampleElement("ORDER_DETAILID",detailBean.getGs_order_detail_id()));
            element.addChildElement(new SampleElement("WAREHOUSE_CODE",detailBean.getGs_workcorp_id()));
            element.addChildElement(new SampleElement("PROVIDER_CODE",detailBean.getCode()));
            element.addChildElement(new SampleElement("SEND_BILL_CODE",goodsId));
            element.addChildElement(new SampleElement("PRODUCT_CODE",detailBean.getGs_concentricity_id()));
            element.addChildElement(new SampleElement("PRODUCT_PRICE",StringUtils.formatEDouble(detailBean.getGs_goods_unitprice(),4)));
            element.addChildElement(new SampleElement("PRODUCT_COUNT",StringUtils.formatEDouble(detailBean.getGs_deliver_goods_counts(),2)));
            element.addChildElement(new SampleElement("PRODUCT_MONEY",StringUtils.formatEDouble(detailBean.getGs_goods_unitprice()*detailBean.getGs_deliver_goods_counts(),4)));
            element.addChildElement(new SampleElement("BALANCE_MODE",detailBean.getGs_balance_mode()));
            result.append(element.toString());
        }
        return result.toString();
    }
    /**
     * 取得系统当前日期
     * @return
     */
    private String getCurDT(){
        String tCurDT = "";
        try{
            tCurDT = DateUtil.formateDateTime(DateUtil.getCurrentTime("DT","AD"));
        }catch(Exception e){
            e.printStackTrace();
        }
        return tCurDT;
    }
}
